package com.hqd.ch03.v18.aop.framework;

import lombok.AllArgsConstructor;
import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.io.Serializable;
import java.lang.reflect.Method;

@AllArgsConstructor
public class ProxyFactory extends AdvisedSupport {
    private Class<?> superClass;
    private Object target;
    private Method method;

    public Object getProxy() {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(superClass);
        /**
         * 添加默认拦截器，执行增强
         */
        enhancer.setCallbacks(new Callback[]{new DynamicAdvisedInterceptor(this, target, method)});
        return enhancer.create();
    }

    @AllArgsConstructor
    private static class DynamicAdvisedInterceptor implements MethodInterceptor, Serializable {
        private AdvisedSupport advisedSupport;
        private Object target;
        private Method method;


        @Override
        public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
            ReflectiveMethodInvocation rmi = new ReflectiveMethodInvocation(target, proxy,
                    this.method, args, advisedSupport.getAdvisors());
            return rmi.proceed();
        }
    }
}
